package com.kukudexin.util;

import com.kukudexin.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 德鑫
 * @description:
 * @since: 2021/5/27
 */
@Component
public class HttpParseUtil {
    public static void main(String[] args) throws IOException {
        HttpParseUtil httpParseUtil = new HttpParseUtil();
        httpParseUtil.parseJD("java");
    }

    public List<Content> parseJD(String keyword) throws IOException {
        String url = "https://uland.taobao.com/sem/tbsearch?keyword=" + keyword + "&enc=utf-8";
        Document document = Jsoup.parse(new URL(url), 30000);
        System.out.println(document);
//        Element element = document.getElementById("J_goodsList");
        Elements elements = document.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();

        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            if (price.length()>0) {
                goodsList.add(new Content(title, img, price));
            }
        }
        return goodsList;
    }
}
